<template>
  <div class="search-bar">
    <div class="select-bar" style="margin-bottom: 20px">
      <div class="select-item">
        <label for="templateCode-input">模版CODE：</label>
        <input
          id="templateCode-input"
          placeholder="输入模版CODE"
          v-model="queryInfo.templateCode"
          class="input-field"
          style="height: 30px"
        />
      </div>

      <div class="select-item">
        <label for="templateContent-input">模版内容：</label>
        <input
          id="templateContent-input"
          placeholder="输入模版内容"
          v-model="queryInfo.templateContent"
          class="input-field"
          style="height: 30px"
        />
      </div>
      <el-button type="primary" @click="getGongYing()" class="search-button">
        <i class="fas fa-search"></i>查询
      </el-button>
      <el-button type="primary" @click="handleReset" class="reset-button">
        <i class="fas fa-undo"></i>重置
      </el-button>
      <el-button type="default" @click="toggleExpand" class="toggle-button">
        {{ isExpanded ? "收起" : "展开" }}
        <i :class="isExpanded ? 'fas fa-angle-up' : 'fas fa-angle-down'"></i>
      </el-button>
      <div v-if="isExpanded" class="expand-content">
        <div class="select-item" style="display: inline-block">
          <label for="templateName-input">模版标题：</label>
          <input
            id="templateName-input"
            placeholder="输入模版标题"
            v-model="queryInfo.templateName"
            class="input-field"
            style="display: inline-block; height: 30px; margin-top: 15px"
          />
        </div>
        <div class="select-item" style="display: inline-block">
          <label for="templateType-input">模版类型：</label>
          <input
            id="templateType-input"
            placeholder="输入模版类型"
            v-model="queryInfo.templateType"
            class="input-field"
            style="display: inline-block; height: 30px; margin-top: 15px"
          />
        </div>
      </div>
    </div>
    <div class="xinzeng">
      <el-button type="text" @click="addShowInit()">
        <i class="fas fa-plus"></i>新增
      </el-button>
      <el-button type="text" @click="exportExcel">
        <i class="el-icon-download"></i>导出
      </el-button>
      <el-upload
        action
        :show-file-list="false"
        :on-change="importExcel"
        :auto-upload="false"
      >
        <el-button icon="upload" type="text" size="small">
          <i class="fas fa-file-import"></i>导入
        </el-button>
      </el-upload>
      <el-dropdown type="primary" size="medium" v-if="selectedRows.length > 0">
        <span class="el-dropdown-link" style="color: rgba(0, 0, 0, 0.65)">
          批量操作<i class="el-icon-arrow-down el-icon--right"></i>
        </span>
        <el-dropdown-menu slot="dropdown">
          <el-button
            type="text"
            style="color: rgba(0, 0, 0, 0.65); margin: 0 5px"
            @click="batchDelete"
            ><i class="fas fa-trash"></i>
            删除
          </el-button>
        </el-dropdown-menu>
      </el-dropdown>
    </div>
    <p>
      已选择<span style="color: #1890ff">{{ selectedRows.length }}</span
      >项
      <el-button
        type="text"
        @click="handleReset"
        class="reset-button"
        style="border: none; color: #1890ff; background-color: #e6f7ff"
      >
        清空
      </el-button>
    </p>
    <el-table
      :data="list"
      border
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column label="#" type="index" width="50"></el-table-column>
      <el-table-column
        label="模版CODE"
        width="120"
        prop="templateCode"
      ></el-table-column>
      <el-table-column label="模版标题" prop="templateName"></el-table-column>
      <el-table-column
        label="模版内容"
        prop="templateContent"
      ></el-table-column>
      <el-table-column label="模版类型">
        <template slot-scope="scope">
          <span
            v-if="scope.row.templateType == 0"
            style="color: #333"
            type="text"
            >系统</span
          >
          <span
            v-else-if="scope.row.templateType == 1"
            style="color: #333"
            type="text"
            >短信</span
          >
          <span
            v-else-if="scope.row.templateType == 2"
            style="color: #333"
            type="text"
            >邮件</span
          >
          <span v-else type="text" style="color: #333">微信</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="150">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            style="color: #1890ff"
            @click="handleEdit(scope.row)"
          >
            编辑
          </el-button>
          <span style="color: #bbb; margin-right: 3px">|</span>
          <el-dropdown size="small">
            <span class="el-dropdown-link" style="color: #1890ff">
              更多<i class="el-icon-arrow-down el-icon-- right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item>
                <el-button
                  size="mini"
                  type="text"
                  style="color: rgba(0, 0, 0, 0.65); margin: 0 5px"
                  @click="handleDelete(scope.row)"
                >
                  删除
                </el-button>
              </el-dropdown-item>
              <el-dropdown-item>
                <el-button
                  size="mini"
                  type="text"
                  style="color: rgba(0, 0, 0, 0.65); margin: 0 5px"
                  @click="handlesend(scope.row)"
                >
                  发送测试
                </el-button>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <!-- 添加或者编辑募捐团队模态框 -->
    <el-dialog :title="id ? '编辑' : '新增'" :visible.sync="dialogFormVisible">
      <el-form
        :model="listForm"
        :rules="rules"
        ref="listForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="模版CODE" prop="templateCode">
              <el-input
                v-model="listForm.templateCode"
                @change="checkCode()"
                :disabled="id == null ? false : true"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="模版类型"
              style="display: block; margin-bottom: 15px"
            >
              <el-select
                v-model="listForm.templateType"
                placeholder="请选择模版类型"
              >
                <el-option
                  v-for="(item, index) in fangshi"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="模版标题" prop="templateName">
          <el-input v-model="listForm.templateName"></el-input>
        </el-form-item>
        <el-form-item label="模版内容" prop="templateContent">
          <textarea
            name=""
            id=""
            cols="60"
            rows="10"
            v-model="listForm.templateContent"
          ></textarea>
        </el-form-item>
        <el-form-item class="btns">
          <el-button @click="resetForm('listForm')" style="margin-right: 10px">
            取消
          </el-button>
          <el-button v-if="id" type="primary" @click="editForm('listForm')">
            确定
          </el-button>
          <el-button v-else type="primary" @click="addForm('listForm')">
            确定
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 发送测试 -->
    <el-dialog title="发送测试" :visible.sync="Visible">
      <el-form
        :model="listForm"
        :rules="rules"
        ref="listForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="模版标题" prop="templateName">
          <el-input
            v-model="listForm.templateName"
            @change="checkCode()"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="模版内容" prop="templateContent">
          <textarea
            name=""
            id=""
            cols="60"
            rows="10"
            v-model="listForm.templateContent"
            disabled
          ></textarea>
        </el-form-item>
        <el-form-item label="测试数据" prop="testData">
          <textarea
            name=""
            id=""
            cols="60"
            rows="10"
            v-model="listForm.testData"
          ></textarea>
        </el-form-item>
        <el-form-item
          label="消息类型"
          style="display: block; margin-bottom: 15px"
        >
          <el-select v-model="listForm.msgType" placeholder="请选择消息类型">
            <el-option
              v-for="(item, index) in fangshi"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="消息接收方"
          prop="receiver"
          style="display: block; margin-bottom: 15px"
        >
          <el-input v-model="listForm.receiver"></el-input>
        </el-form-item>
        <el-form-item class="btns">
          <el-button @click="resetForm('listForm')" style="margin-right: 10px">
            取消
          </el-button>
          <el-button type="primary" @click="sendForm('listForm')"
            >确定</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>
    <pagination
      :page="queryInfo.pageNo"
      :componentTotal="total"
      @changeRows="setPageSize"
      @changePage="setPageNo"
    ></pagination>
  </div>
</template>

<script>
import { Button } from "element-ui";
import axios from "axios";
import Pagination from "../Pagination.vue";
import { excelExportUseJson, excelImport } from "../../assets/js/xlsx";

export default {
  components: {
    "el-button": Button,
    Pagination,
  },
  data() {
    return {
      search1: "",
      search2: "",
      isExpanded: false,
      direction: "rtl",
      queryInfo: {
        _t: "",
        column: "createTime",
        order: "desc",
        field:
          "id,,,esTitle,esContent,esReceiver,esSendNum,esSendStatus_dictText,esSendTime,esType_dictText,action",
        pageNo: 1,
        pageSize: 10,
      },
      data: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      listHeader: {
        templateCode: "模版CODE",
        templateName: "模版标题",
        templateContent: "模版内容",
        templateTestJson: "模版测试json",
        templateType: "模版类型",
        createBy: "创建人",
        createTime: "创建时间",
        updateBy: "更新人",
        updateTime: "更新时间",
      },
      list: [],
      total: 0,
      loading: false,
      listForm: {
        createBy: "",
        createTime: "",
        id: "",
        templateCode: "",
        templateContent: "",
        templateName: "",
        templateTestJson: "",
        templateType: "",
        updateBy: "",
        updateTime: "",
      },
      dialogFormVisible: false,
      Visible: false,
      id: null,
      options: [],
      rules: {
        templateCode: [
          { required: true, message: "请输入模版CODE", trigger: "blur" },
        ],
        templateType: [
          { required: true, message: "请输入模版类型", trigger: "blur" },
        ],
        templateName: [
          { required: true, message: "请输入模版标题", trigger: "blur" },
        ],
      },
      fangshi: [
        { label: "系统", value: "0" },
        { label: "短信", value: "1" },
        { label: "邮箱", value: "2" },
        { label: "微信", value: "3" },
      ],
      sendsForm: {
        msgType: "",
        receiver: "",
        templateCode: "",
        testData: "",
      },
      selectedRows: [],
      selectedCount: 0,
      querychange: {
        _t: new Date().getTime(),
        tableName: "sys_sms_template",
        fieldName: "template_code",
        fieldVal: "",
      },
    };
  },
  mounted() {
    this.getGongYing();
  },
  methods: {
    // 发送测试validate
    async handlesend(row) {
      this.sendsForm.templateCode = row.templateCode;
      this.listForm = { ...row };
      this.Visible = true;
      this.id = row.id;
    },
    sendForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (!valid) return false;
        try {
          const res = await axios.post(
            "http://8.142.74.15:48082/jeecg-boot/message/sysMessageTemplate/sendMsg",
            this.sendsForm
          );
          console.log(res);
          this.Visible = false;
          this.getGongYing();
        } catch (err) {
          console.log(err);
          this.$message.error("发送失败，请重试。");
        }
      });
    },
    // 模版CODE
    async checkCode() {
      this.loading = true; // 设置加载状态
      this.queryInfo._t = new Date().getTime(); // 防止缓存
      try {
        const { data: res } = await axios.get(
          "http://8.142.74.15:48082/jeecg-boot/sys/duplicate/check",
          {
            params: this.querychange,
          }
        );

        if (res.code !== 200) {
          this.$message.error("获取任务管理列表失败");
          return;
        }
      } catch (error) {
        console.error("Error fetching data:", error);
        this.$message.error("请求数据失败，请重试。");
      } finally {
        this.loading = false; // 取消加载状态
      }
    },
    // 导出
    exportExcel() {
      excelExportUseJson(this.list, this.listHeader, "消息模版");
    },
    // 导入
    importExcel(file) {
      console.log(file);
      excelImport(file.raw, "json").then((res) => {
        res = res.map((item) => {
          let newUserFrom = {};
          for (let [headerKey, headerVal] of Object.entries(this.listHeader)) {
            newUserFrom[headerKey] = item[headerVal];
          }
          newUserFrom.passWord = "123456";
          return newUserFrom;
        });
        console.log(res);
      });
    },
    handleNodeClick(data) {
      console.log(data);
    },
    // 添加任务
    addShowInit() {
      this.dialogFormVisible = true;
      this.id = null;
      this.listForm = {
        templateCode: "",
        templateType: "",
        templateName: "",
        templateContent: "",
      };
    },
    addForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (!valid) return false;
        await this.axios
          .post(
            "http://8.142.74.15:48082/jeecg-boot/message/sysMessageTemplate/add",
            this.listForm
          )
          .then((res) => {
            console.log(res);
            this.dialogFormVisible = false;
            this.getGongYing();
          })
          .catch((err) => {
            console.log(err);
            this.$message.error("添加失败，请重试。");
          });
      });
    },
    // 编辑任务
    async handleEdit(row) {
      this.listForm = { ...row };
      this.dialogFormVisible = true;
      this.id = row.id;
    },
    editForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (!valid) return false;
        await this.axios
          .put(
            "http://8.142.74.15:48082/jeecg-boot/message/sysMessageTemplate/edit",
            this.listForm
          )
          .then((res) => {
            console.log(res);
            this.dialogFormVisible = false;
            this.getGongYing();
          })
          .catch((err) => {
            console.log(err);
            this.$message.error("编辑失败，请重试。");
          });
      });
    },
    //取消重置
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.dialogFormVisible = false;
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then(() => {
          done();
        })
        .catch(() => {});
    },
    // 删除任务
    handleDelete(row) {
      console.log(row);
      this.$confirm("是否删除该条数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.deleteSamplereport(row.id);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    async deleteSamplereport(id) {
      await this.axios
        .delete(
          `http://8.142.74.15:48082/jeecg-boot/message/sysMessageTemplate/delete?id=${id}`
        )
        .then((res) => {
          console.log(res);
          this.getGongYing();
          window.location.reload();
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 查询列表
    async getGongYing() {
      this.loading = true; // 设置加载状态
      this.queryInfo._t = new Date().getTime(); // 防止缓存
      try {
        const { data: res } = await axios.get(
          "http://8.142.74.15:48082/jeecg-boot/message/sysMessageTemplate/list",
          {
            params: this.queryInfo,
          }
        );

        if (res.code !== 200) {
          this.$message.error("获取任务管理列表失败");
          return;
        }
        this.list = res.result.records; // 获取记录
        this.total = res.result.total; // 获取总数
      } catch (error) {
        console.error("Error fetching data:", error);
        this.$message.error("请求数据失败，请重试。");
      } finally {
        this.loading = false; // 取消加载状态
      }
    },
    // 分页器
    setPageSize(val) {
      this.queryInfo.pageSize = val;
      this.getGongYing();
    },
    setPageNo(val) {
      this.queryInfo.pageNo = val;
      this.getGongYing();
    },
    handleReset() {
      this.search1 = "";
      this.search2 = "";
      this.queryInfo.code = "";
      this.queryInfo.name = "";
      this.queryInfo.pageNo = 1;
      this.queryInfo.pageSize = 10;
      this.getGongYing(); // 重置后重新获取数据
    },
    toggleExpand() {
      this.isExpanded = !this.isExpanded; // 切换展开状态
    },
    // 处理表格行选择变化
    handleSelectionChange(selections) {
      this.selectedRows = selections;
      this.selectedCount = selections.length;
    },
    async batchDelete() {
      if (this.selectedRows.length === 0) {
        return;
      }
      const ids = this.selectedRows.map((row) => row.id);
      try {
        // 修改请求URL中的参数
        await axios.delete(
          `http://8.142.74.15:48082/jeecg-boot/message/sysMessageTemplate/deleteBatch?ids=${ids}`,
          {
            data: { ids: ids },
          }
        );
        this.$message.success("批量删除成功");
        this.getGongYing();
      } catch (error) {
        console.error("批量删除失败:", error);
        // 提供更详细的错误信息给用户
        if (error.response && error.response.status === 404) {
          this.$message.error("请求的资源不存在，批量删除失败");
        } else if (error.response && error.response.status === 500) {
          this.$message.error("服务器内部错误，批量删除失败");
        } else {
          this.$message.error("批量删除失败，请重试");
        }
      }
    },
  },
};
</script>

<style scoped>
.search-bar {
  height: 100%;
  margin: 0;
  padding: 8px 24px;
  color: rgba(0, 0, 0, 0.65);
  font-size: 14px;
  list-style: none;
  background-color: #fff;
  transition: all 0.3s;
  border-radius: 2px;
}

.search-bar p {
  display: block;
  line-height: 40px;
  width: 100%;
  height: 40px;
  background-color: #e6f7ff;
  border: 1px solid #91d5ff;
  margin-bottom: 15px;
  padding-left: 10px;
  border-radius: 3px;
}
.select-bar {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.select-item {
  display: flex;
  align-items: center;
  padding: 0 12px;
  /* width: 384px; */
}

label {
  width: 150px;
  color: #000;
  margin-right: 8px;
}

.input-field {
  width: 335px;
  height: 22px;
  padding: 4px 11px;
  border-radius: 5px;
  border: 1px solid #d9d9d9;
  transition: border-color 0.3s; /* 边框颜色变化过渡 */
  outline: none; /* 移除默认轮廓 */
}

/* 输入框鼠标悬停效果 */
.input-field:hover {
  border-color: #409eff; /* 悬停时边框颜色 */
}

/* 输入框获得焦点时的样式 */
.input-field:focus {
  border-color: #409eff; /* 焦点时边框颜色 */
  box-shadow: 0 0 5px rgba(64, 158, 255, 0.5); /* 焦点时阴影 */
}

/* 按钮样式 */
.search-button,
.reset-button,
.toggle-button,
.submit-button {
  padding: 10px 15px; /* 内边距 */
  border-radius: 4px; /* 圆角 */
  transition: background-color 0.3s; /* 背景颜色变化过渡 */
}

/* 查询按钮 */
.search-button {
  background-color: #409eff; /* 主色调 */
  color: white; /* 字体颜色 */
  border: 1px solid #409eff;
  width: 82px;
  height: 32px;
  line-height: 12px;
}

/* 查询按钮悬停效果 */
.search-button:hover {
  background-color: #66b1ff; /* 悬停时背景色 */
  border-color: #66b1ff;
}

/* 重置按钮 */
.reset-button {
  background-color: #fff; /* 重置按钮背景 */
  color: rgba(0, 0, 0, 0.65); /* 字体颜色 */
  border: 1px solid #d9d9d9;
  width: 82px;
  height: 32px;
  line-height: 12px;
  margin-left: 8px;
  padding: 0 15px;
  transition: all 0.3s;
}

/* 重置按钮悬停效果 */
.reset-button:hover {
  background-color: #e6f7ff; /* 悬停时背景色 */
  border-color: #409eff;
  color: #409eff;
}

/* 提交按钮 */
.submit-button {
  background-color: #fff; /* 提交按钮背景 */
  color: rgba(0, 0, 0, 0.65); /* 字体颜色 */
  border: 1px solid #d9d9d9;
  width: 82px;
  height: 32px;
  line-height: 12px;
  margin-left: 8px;
  padding: 0 15px;
  transition: all 0.3s;
}

/* 提交按钮悬停效果 */
.submit-button:hover {
  background-color: #e6f7ff; /* 悬停时背景色 */
  border-color: #409eff;
  color: #409eff;
}

/* 图标样式 */
.search-button i,
.reset-button i,
.toggle-button i,
.submit-button i {
  margin-right: 5px; /* 图标与文本之间的间距 */
}
.toggle-button {
  border: none;
  background-color: #fff;
  color: #409eff;
}
/* xinzeng */
.xinzeng {
  display: flex;
  width: 300px;
  align-items: center;
}
.el-button {
  margin-right: 10px;
}
.el-button i {
  margin-right: 5px;
}
.shanchu:hover {
  background-color: #096ba0;
  color: #096dd9;
}
/* 展开内容的样式 */
/*.expand-content {
          margin-top: 10px;
          padding: 10px;
          border: 1px solid #d9d9d9;
          border-radius: 4px;
          background-color: #f9f9f9;
        } */
</style>
